<template>
  <div>
    <!-- 搜索栏 -->
    <a-card style="margin-bottom: 16px;">
      <a-form layout="inline">
        <a-form-item label="关键词">
          <a-input
            v-model:value="searchForm.keyword"
            placeholder="车牌号/客户"
            style="width: 180px;"
            @pressEnter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="全部"
            style="width: 120px;"
            allow-clear
          >
            <a-select-option value="pending">待维修</a-select-option>
            <a-select-option value="repairing">维修中</a-select-option>
            <a-select-option value="completed">已完成</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="开始时间">
          <a-date-picker
            v-model:value="searchForm.startTime"
            placeholder="请选择"
            style="width: 150px;"
          />
        </a-form-item>
        <a-form-item label="结束时间">
          <a-date-picker
            v-model:value="searchForm.endTime"
            placeholder="请选择"
            style="width: 150px;"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <SearchOutlined />
              查询
            </a-button>
            <a-button @click="handleReset">
              <RedoOutlined />
              重置
            </a-button>
            <a-button type="primary" @click="handleAdd">
              <PlusOutlined />
              新增
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 表格 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag v-if="record.status === 'pending'" color="orange">待维修</a-tag>
            <a-tag v-else-if="record.status === 'repairing'" color="blue">维修中</a-tag>
            <a-tag v-else-if="record.status === 'completed'" color="green">已完成</a-tag>
          </template>
          <template v-if="column.key === 'cost'">
            <span style="color: #f5222d; font-weight: bold;">¥{{ record.cost }}</span>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-dropdown>
                <a-button type="link" size="small">
                  状态 <DownOutlined />
                </a-button>
                <template #overlay>
                  <a-menu @click="({ key }) => handleStatusChange(record.id, key)">
                    <a-menu-item key="pending">待维修</a-menu-item>
                    <a-menu-item key="repairing">维修中</a-menu-item>
                    <a-menu-item key="completed">已完成</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-popconfirm
                title="确定删除该记录吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record.id)"
              >
                <a-button type="link" danger size="small">
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      width="800px"
    >
      <a-form :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="车辆" required>
          <a-select
            v-model:value="formData.vehicleId"
            placeholder="请选择车辆"
            show-search
            :filter-option="filterOption"
            @change="handleVehicleChange"
          >
            <a-select-option v-for="vehicle in vehicleList" :key="vehicle.id" :value="vehicle.id" :vehicle="vehicle">
              {{ vehicle.plateNumber }} - {{ vehicle.brand }} {{ vehicle.model }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="故障描述" required>
          <a-textarea v-model:value="formData.faultDescription" placeholder="请详细描述故障现象" :rows="3" />
        </a-form-item>
        <a-form-item label="维修方案">
          <a-textarea v-model:value="formData.repairPlan" placeholder="请输入维修方案" :rows="3" />
        </a-form-item>
        <a-form-item label="维修项目">
          <a-textarea v-model:value="formData.repairItems" placeholder="请输入维修项目" :rows="2" />
        </a-form-item>
        <a-form-item label="开始时间" required>
          <a-date-picker
            v-model:value="formData.startTime"
            show-time
            style="width: 100%;"
            placeholder="请选择开始时间"
          />
        </a-form-item>
        <a-form-item label="完成时间">
          <a-date-picker
            v-model:value="formData.endTime"
            show-time
            style="width: 100%;"
            placeholder="请选择完成时间"
          />
        </a-form-item>
        <a-form-item label="维修状态" required>
          <a-select v-model:value="formData.status" placeholder="请选择状态">
            <a-select-option value="pending">待维修</a-select-option>
            <a-select-option value="repairing">维修中</a-select-option>
            <a-select-option value="completed">已完成</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="维修费用" required>
          <a-input-number
            v-model:value="formData.cost"
            :min="0"
            :precision="2"
            placeholder="元"
            style="width: 100%;"
          />
        </a-form-item>
        <a-form-item label="维修人员">
          <a-input v-model:value="formData.operator" placeholder="请输入维修人员" />
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea v-model:value="formData.remark" placeholder="请输入备注" :rows="2" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  getRepairPage,
  addRepair,
  updateRepair,
  updateRepairStatus,
  deleteRepair
} from '@/api/repair'
import { getVehiclePage } from '@/api/vehicle'
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined,
  DownOutlined
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'

const loading = ref(false)
const tableData = ref([])
const vehicleList = ref([])
const searchForm = reactive({
  keyword: '',
  status: undefined,
  startTime: null,
  endTime: null
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: total => `共 ${total} 条`
})

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 70 },
  { title: '车牌号', dataIndex: 'plateNumber', key: 'plateNumber', width: 100 },
  { title: '客户', dataIndex: 'customerName', key: 'customerName', width: 100 },
  { title: '故障描述', dataIndex: 'faultDescription', key: 'faultDescription', ellipsis: true },
  { title: '开始时间', dataIndex: 'startTime', key: 'startTime', width: 160 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '费用', dataIndex: 'cost', key: 'cost', width: 100 },
  { title: '维修人员', dataIndex: 'operator', key: 'operator', width: 90 },
  { title: '操作', key: 'action', width: 200, fixed: 'right' }
]

const modalVisible = ref(false)
const modalLoading = ref(false)
const modalTitle = ref('新增维修记录')
const isEdit = ref(false)
const formData = reactive({
  id: null,
  vehicleId: null,
  customerId: null,
  faultDescription: '',
  repairPlan: '',
  repairItems: '',
  startTime: null,
  endTime: null,
  status: 'pending',
  cost: 0,
  operator: '',
  remark: ''
})

// 加载车辆列表
const loadVehicleList = async () => {
  try {
    const res = await getVehiclePage({ current: 1, size: 1000 })
    vehicleList.value = res.data.records
  } catch (error) {
    console.error('加载车辆列表失败：', error)
  }
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    const res = await getRepairPage({
      current: pagination.current,
      size: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status,
      startTime: searchForm.startTime ? dayjs(searchForm.startTime).format('YYYY-MM-DD') : null,
      endTime: searchForm.endTime ? dayjs(searchForm.endTime).format('YYYY-MM-DD') : null
    })
    tableData.value = res.data.records
    pagination.total = res.data.total
  } catch (error) {
    console.error('加载数据失败：', error)
  } finally {
    loading.value = false
  }
}

// 车辆选择变化
const handleVehicleChange = (value) => {
  const vehicle = vehicleList.value.find(v => v.id === value)
  if (vehicle) {
    formData.customerId = vehicle.customerId
  }
}

// 查询
const handleSearch = () => {
  pagination.current = 1
  loadTableData()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = undefined
  searchForm.startTime = null
  searchForm.endTime = null
  pagination.current = 1
  loadTableData()
}

// 表格分页变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadTableData()
}

// 新增
const handleAdd = () => {
  modalTitle.value = '新增维修记录'
  isEdit.value = false
  Object.assign(formData, {
    id: null,
    vehicleId: null,
    customerId: null,
    faultDescription: '',
    repairPlan: '',
    repairItems: '',
    startTime: dayjs(),
    endTime: null,
    status: 'pending',
    cost: 0,
    operator: '',
    remark: ''
  })
  modalVisible.value = true
}

// 编辑
const handleEdit = (record) => {
  modalTitle.value = '编辑维修记录'
  isEdit.value = true
  Object.assign(formData, {
    ...record,
    startTime: record.startTime ? dayjs(record.startTime) : null,
    endTime: record.endTime ? dayjs(record.endTime) : null
  })
  modalVisible.value = true
}

// 状态变更
const handleStatusChange = async (id, status) => {
  try {
    await updateRepairStatus(id, status)
    message.success('状态更新成功')
    loadTableData()
  } catch (error) {
    console.error('状态更新失败：', error)
  }
}

// 删除
const handleDelete = async (id) => {
  try {
    await deleteRepair(id)
    message.success('删除成功')
    loadTableData()
  } catch (error) {
    console.error('删除失败：', error)
  }
}

// 弹窗确认
const handleModalOk = async () => {
  if (!formData.vehicleId || !formData.faultDescription || !formData.startTime || !formData.status) {
    message.warning('请填写必填项')
    return
  }
  
  modalLoading.value = true
  try {
    const data = {
      ...formData,
      startTime: formData.startTime ? dayjs(formData.startTime).format('YYYY-MM-DD HH:mm:ss') : null,
      endTime: formData.endTime ? dayjs(formData.endTime).format('YYYY-MM-DD HH:mm:ss') : null
    }
    
    if (isEdit.value) {
      await updateRepair(data)
      message.success('更新成功')
    } else {
      await addRepair(data)
      message.success('新增成功')
    }
    modalVisible.value = false
    loadTableData()
  } catch (error) {
    console.error('操作失败：', error)
  } finally {
    modalLoading.value = false
  }
}

// 选择器筛选
const filterOption = (input, option) => {
  return option.children[0].children.toLowerCase().includes(input.toLowerCase())
}

onMounted(() => {
  loadVehicleList()
  loadTableData()
})
</script>

<style scoped>
</style>

